package com.zhang.authority.model;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;

import java.util.Date;
import java.util.Objects;

/**
 * description
 *
 * @author zhangFanJun
 * @date 2023-12-07 17:18
 **/
public class PrincipalBuilder {

    private PrincipalBuilder() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * 业务中台内部
     */
    public static final String ISSUER_INNER = "inner";
    /**
     * 对接外部
     */
    public static final String ISSUER_OPEN = "open";

    /**
     * token解析封装上下文
     */
    public static Principal getInstance(String issuer, String audience, String subject, Date expiration, String info) {
        if (Objects.equals(issuer, ISSUER_INNER)) {
            UserDTO userDetail = JSON.parseObject(info, UserDTO.class);
            Principal<UserDTO> res = new Principal<>();
            res.setIssuer(issuer);
            res.setAudience(audience);
            res.setSubject(subject);
            res.setInfo(userDetail);
            res.setExpiration(expiration);
            res.setExpire(DateUtil.between(new Date(), expiration, DateUnit.SECOND, true));
            return res;
        }

        if (Objects.equals(issuer, ISSUER_OPEN)) {
            OpenAccountDO openAccountDO = JSON.parseObject(info, OpenAccountDO.class);
            Principal<OpenAccountDO> res = new Principal<>();
            res.setIssuer(issuer);
            res.setAudience(audience);
            res.setSubject(subject);
            res.setInfo(openAccountDO);
            res.setExpiration(expiration);
            res.setExpire(DateUtil.between(new Date(), expiration, DateUnit.SECOND, true));
            return res;
        }
        return null;
    }

    public static <T> Principal<T> getInstance(String issuer, String audience, String subject, T info) {
        Principal res = new Principal<>();
        res.setIssuer(issuer);
        res.setAudience(audience);
        res.setSubject(subject);
        res.setInfo(info);
        return res;
    }
}
